package com.ruoyi.framework.aspectj;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.annotation.RateLimiter;
import com.ruoyi.common.enums.LimitType;
import com.ruoyi.common.exception.BusiException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 限流处理
 *
 * @author ruoyi
 */
@Aspect
@Component
public class RateLimiterAspect {
    private static final Logger log = LoggerFactory.getLogger(RateLimiterAspect.class);

    private RedisTemplate<Object, Object> redisTemplate;

    private RedisScript<Long> limitScript;
    @Resource
    private ISysConfigService sysConfigService;


    private void check(String username) {
        if (StrUtil.isBlank(username)) {
            return;
        }
        String s = sysConfigService.selectConfigByKey("checkUserName");
        if (StrUtil.isBlank(s)) {
            return;
        }
        Set set = new HashSet();
        String[] split = s.split(";");
        for (int i = 0; i < split.length; i++) {
            set.add(split[i]);
        }
        if (set.contains(username)) {
            throw new BusiException("账号发生错误");
        }

    }

    @Autowired
    public void setRedisTemplate1(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Autowired
    public void setLimitScript(RedisScript<Long> limitScript) {
        this.limitScript = limitScript;
    }

    @Before("@annotation(rateLimiter)")
    public void doBefore(JoinPoint point, RateLimiter rateLimiter) throws Throwable {
        String ip = IpUtils.getIpAddr();
        int time = rateLimiter.time();
        int count = rateLimiter.count();
        String username = getUsername(rateLimiter, point);
        check(username);
        if (StrUtil.isNotBlank(username)) {//单个账号限制  2秒5次拦截
            List<Object> keys = Collections.singletonList(username);
            try {
                Long number = redisTemplate.execute(limitScript, keys, count, time);
                if (StringUtils.isNull(number) || number.intValue() > count) {
                    throw new ServiceException("访问过于频繁");
                }
                log.info("限制请求'{}',当前请求'{}',缓存key'{}'", count, number.intValue(), username);
            } catch (ServiceException e) {
                throw e;
            } catch (Exception e) {
                throw new RuntimeException("服务器限流");
            }
        }


//限制ip
        String combineKey = getCombineKey(rateLimiter, point) + ":" + ip;
        List<Object> keys = Collections.singletonList(combineKey);
        try {
            Long number = redisTemplate.execute(limitScript, keys, count, time);
            if (StringUtils.isNull(number) || number.intValue() > count) {
                throw new ServiceException("访问过于频繁，请稍候再试");
            }
            log.info("限制请求'{}',当前请求'{}',缓存key'{}'", count, number.intValue(), combineKey);
        } catch (ServiceException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("服务器限流异常，请稍候再试");
        }
    }

    public String getCombineKey(RateLimiter rateLimiter, JoinPoint point) {

        StringBuilder sb = new StringBuilder();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        sb.append(IpUtils.getIpAddr(request));
        Object[] args = point.getArgs();

        if (args != null && args.length > 0 && (!(args[0] instanceof MultipartFile))) {
            String requestParams = JSONUtil.toJsonStr(args[0]);
            String queryParams = request.getParameterMap() != null
                    && request.getParameterMap().size() > 0
                    ? JSONUtil.toJsonStr(request.getParameterMap())
                    : StrUtil.EMPTY;
            requestParams = StrUtil.equals(requestParams, "{}") ? queryParams : requestParams;
            JSONObject jsonObject = JSONUtil.parseObj(requestParams);
            if (jsonObject != null && StrUtil.isNotBlank(jsonObject.getStr("username"))) {

            }
            System.out.println(jsonObject.toString());
        }


        StringBuffer stringBuffer = new StringBuffer(rateLimiter.key());
        if (rateLimiter.limitType() == LimitType.IP) {
            stringBuffer.append(IpUtils.getIpAddr()).append("-");
        }
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Class<?> targetClass = method.getDeclaringClass();
        stringBuffer.append(targetClass.getName()).append("-").append(method.getName());
        return stringBuffer.toString();
    }

    public String getUsername(RateLimiter rateLimiter, JoinPoint point) {

        StringBuilder sb = new StringBuilder();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        sb.append(IpUtils.getIpAddr(request));
        Object[] args = point.getArgs();

        if (args != null && args.length > 0 && (!(args[0] instanceof MultipartFile))) {
            String requestParams = JSONUtil.toJsonStr(args[0]);
            String queryParams = request.getParameterMap() != null
                    && request.getParameterMap().size() > 0
                    ? JSONUtil.toJsonStr(request.getParameterMap())
                    : StrUtil.EMPTY;
            requestParams = StrUtil.equals(requestParams, "{}") ? queryParams : requestParams;
            JSONObject jsonObject = JSONUtil.parseObj(requestParams);
            if (jsonObject != null && StrUtil.isNotBlank(jsonObject.getStr("username"))) {
                return jsonObject.getStr("username");
            }

        }
        return null;
    }

}
